<?php
/**
 * Name: 管理员模型
 * User: 董坤鸿
 * Date: 2017/9/13
 * Time: 下午12:58
 */

namespace app\model;

use think\Loader;
use think\Model;
use think\Validate;

class Admins extends Model
{
    protected $pk = 'id';
    protected $table = 'g_admins';
    protected $insert = ['created_at'];
    protected $update = ['updated_at'];


    /**
     * 创建时间
     *
     * @param $value
     * @return false|string
     */
    protected function setCreatedAtAttr($value)
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 修改时间
     *
     * @param $value
     * @return false|string
     */
    protected function setUpdatedAtAttr($value)
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 登录
     *
     * @param $data
     * @return array
     */
    public function login($data)
    {
        //1.执行验证
        $validate = Loader::validate('Admins');
        //如果验证不通过
        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
        //2.比对用户名和密码是否正确
        $user_info = $this->where('mobile', $data['mobile'])->where('password', md5(md5($data['password'])))->find();
        if (!$user_info) {
            //说明在数据库未匹配到相关数据
            return ['valid' => 0, 'msg' => '用户名或者密码不正确'];
        }
        //3.将用户信息存入到session中
        session('admin.id', $user_info['id']);
        session('admin.mobile', $user_info['mobile']);
        session('admin.username', $user_info['username']);
        return ['valid' => 1, 'msg' => '登录成功'];
    }

    /**
     * 修改密码
     *
     * @param $data
     * @return array
     */
    public function password($data)
    {
        //1.执行验证
        $validate = new Validate([
            'old_password' => 'require',
            'new_password' => 'require',
            'confirm_password' => 'require|confirm:new_password'
        ], [
            'old_password.require' => '请输入原始密码',
            'new_password.require' => '请输入新密码',
            'confirm_password.require' => '请输入确认密码',
            'confirm_password.confirm' => '确认密码跟新密码不一致',
        ]);

        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
        //2.原始是否正确
        $user_info = $this->where('id', session('admin.id'))->where('password', md5(md5($data['old_password'])))->find();
        if (!$user_info) {
            return ['valid' => 0, 'msg' => '原始密码不正确'];
        }
        //3.修改密码
        //save方法第二个参数为更新条件
        $res = $this->save([
            'password' => md5(md5($data['new_password'])),
        ], [$this->pk => session('admin.id')]);
        if ($res) {
            return ['valid' => 1, 'msg' => '密码修改成功'];
        } else {
            return ['valid' => 0, 'msg' => '修改密码失败'];
        }
    }

}